package com.ww.springboot.dd.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2023-03-01 11:05
 */
//@Configuration
@MapperScan(basePackages = {"com.ww.springboot.dd.mapper"}, sqlSessionFactoryRef = "test1SqlSessionFactory")
public class HivDbConfig {


    @Bean(name = "test1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.hive")
    public DataSource getDateSource1() {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        dataSource.setInitialSize(5);
        dataSource.setMaxActive(200);
        dataSource.setMinIdle(5);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("select 1");
        dataSource.setValidationQueryTimeout(2000);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        return dataSource;
    }

    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource,
                                                    ObjectProvider<Interceptor[]> interceptorsProvider) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setPlugins(interceptorsProvider.getIfAvailable());
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/ww/springboot/dd/mapper/*.xml"));
        return bean.getObject();
    }

    @Bean("test1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate test1sqlsessiontemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }

}
